<!-- filepath: e:\Product\my-vue3-project\src\views\Login.vue -->
<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>登录</h2>
      <el-form
        :model="form"
        :rules="rules"
        ref="loginFormRef"
        label-width="5rem"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin">登录</el-button>
          <el-button type="text" @click="goToForgot">忘记密码？</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="text" @click="goToRegister"
            >没有账号？去注册</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/user";
import { useApi } from "@/composables/useApi";
const userStore = useUserStore();
const api = useApi();

const router = useRouter();
const loginFormRef = ref();
const form = ref({
  username: "",
  password: "",
});

const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

const onLogin = async () => {
  loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const res = await api.login({
          username: form.value.username,
          password: form.value.password,
        });
        console.log(res, "testlog");
        if (res?.data?.token) {
          userStore.setToken(res.data.token);
          userStore.username = res.data.username;
          ElMessage.success("登录成功");
          router.push("/");
        }
      } catch (e) {
        ElMessage.error("登录失败");
      }
    }
  });
};

const goToForgot = () => {
  router.push("/forgot");
};

const goToRegister = () => {
  router.push("/register");
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.login-card {
  width: 21.875rem;
}
</style>
